package ptumall.controller;


import io.jsonwebtoken.io.IOException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ptumall.service.OssService;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/public/oss")
public class OssController {
    private final OssService ossService;

    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> handleFileUpload(
            @RequestParam Map<String, MultipartFile> fileMap,
            @RequestParam String userId,
            @RequestParam String fileType) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 参数校验
            if (fileMap.isEmpty()) {
                return errorResponse(400, "未检测到文件参数", response);
            }

            MultipartFile file = fileMap.values().iterator().next();
            if (file.isEmpty()) {
                return errorResponse(400, "文件内容为空", response);
            }

            // 核心上传逻辑
            String fileUrl = ossService.upload(file);

            if (fileUrl != null) {
                response.put("code", 200);
                response.put("message", "文件上传成功");
                response.put("success", true);
                response.put("url", fileUrl);  // 路径返回但不存库
                return ResponseEntity.ok(response);
            } else {
                return errorResponse(500, "文件上传OSS失败", response);
            }
        } catch (Exception e) {
            log.error("文件上传异常: {}", e.getMessage());
            return errorResponse(500, "服务器内部错误", response);
        }
    }

    private ResponseEntity<Map<String, Object>> errorResponse(int code, String msg, Map<String, Object> response) {
        response.put("code", code);
        response.put("message", msg);
        response.put("success", false);
        return ResponseEntity.status(code).body(response);
    }
}

